/**
 * 统计管理器模块
 * 负责统计数据显示和图表管理
 */

class StatisticsManager {
    constructor() {
        this.defectChart = null;
        this.elements = {
            totalProcessed: document.getElementById('totalProcessed'),
            passRate: document.getElementById('passRate'),
            totalNormal: document.getElementById('totalNormal'),
            totalDefective: document.getElementById('totalDefective')
        };
        this.init();
    }

    init() {
        this.initChart();
        this.startPeriodicUpdate();
    }

    initChart() {
        const ctx = document.getElementById('defectChart');
        if (!ctx) return;

        this.defectChart = new Chart(ctx.getContext('2d'), {
            type: 'doughnut',
            data: {
                labels: ['Crazing', 'Inclusion', 'Patches', 'Pitted Surface', 'Rolled-in Scale', 'Scratches'],
                datasets: [{
                    data: [0, 0, 0, 0, 0, 0],
                    backgroundColor: [
                        '#ff6b6b', // Crazing
                        '#4ecdc4', // Inclusion
                        '#45b7d1', // Patches
                        '#f1c40f', // Pitted Surface
                        '#e67e22', // Rolled-in Scale
                        '#2ecc71'  // Scratches
                    ],
                    borderWidth: 2,
                    borderColor: '#fff'
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        position: 'bottom',
                        labels: {
                            padding: 20,
                            usePointStyle: true
                        }
                    }
                }
            }
        });
    }

    updateStatistics(stats) {
        // 更新数字显示
        if (this.elements.totalProcessed) {
            this.elements.totalProcessed.textContent = stats.total_processed || 0;
        }
        if (this.elements.totalNormal) {
            this.elements.totalNormal.textContent = stats.total_normal || 0;
        }
        if (this.elements.totalDefective) {
            this.elements.totalDefective.textContent = stats.total_defective || 0;
        }
        if (this.elements.passRate) {
            const rate = stats.pass_rate || 0;
            this.elements.passRate.textContent = `${rate.toFixed(1) * 100}%`;
        }

        // 更新图表
        if (this.defectChart && stats.defect_counts) {
            this.defectChart.data.datasets[0].data = [
                stats.defect_counts.crazing || 0,
                stats.defect_counts.inclusion || 0,
                stats.defect_counts.patches || 0,
                stats.defect_counts.pitted_surface || 0,
                stats.defect_counts.rolled_in_scale || 0,
                stats.defect_counts.scratches || 0
            ];
            this.defectChart.update();
        }
    }

    async loadStatistics() {
        try {
            const response = await fetch('/api/statistics');
            const stats = await response.json();
            this.updateStatistics(stats);
        } catch (error) {
            console.error('Failed to load statistics:', error);
        }
    }

    startPeriodicUpdate() {
        // 每5秒更新一次统计数据
        setInterval(() => {
            this.loadStatistics();
        }, 5000);
    }

    processStatisticsUpdate(stats) {
        this.updateStatistics(stats);
    }
}

// 导出到全局
window.StatisticsManager = StatisticsManager;